package com.example.easyexcel.listener;

import com.example.easyexcel.dao.AssetTargetInfoMapper;
import com.example.easyexcel.dto.AssetTargetInfo;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

@Slf4j
public class HutoolSheetProcessor {

    private final AssetTargetInfoMapper mapper;
    private final int batchSize;
    private final List<AssetTargetInfo> batchList;
    private final AtomicInteger processedCount;
    private final AtomicInteger failedCount;
    private final AtomicLong assetNoCounter;

    public HutoolSheetProcessor(AssetTargetInfoMapper mapper, int batchSize) {
        this.mapper = mapper;
        this.batchSize = batchSize;
        this.batchList = new ArrayList<>();
        this.processedCount = new AtomicInteger(0);
        this.failedCount = new AtomicInteger(0);
        this.assetNoCounter = new AtomicLong(0);
    }

    /**
     * 处理单个sheet的数据
     */
    public void processSheet(List<List<Object>> sheetData, int sheetIndex) {
        // 跳过表头行（假设第一行是表头）
        for (int rowIndex = 1; rowIndex < sheetData.size(); rowIndex++) {
            List<Object> row = sheetData.get(rowIndex);
            try {
                AssetTargetInfo entity = convertToEntity(row, sheetIndex, rowIndex);
                batchList.add(entity);
                processedCount.incrementAndGet();

                if (batchList.size() >= batchSize) {
                    saveBatchData();
                }
            } catch (Exception e) {
                failedCount.incrementAndGet();
                log.error("Sheet[{}] 第{}行数据处理失败: {}", sheetIndex, rowIndex + 1, e.getMessage());
            }
        }

        // 处理最后一批数据
        if (!batchList.isEmpty()) {
            saveBatchData();
        }
    }

    /**
     * 批量保存数据
     */
    private void saveBatchData() {
        if (batchList.isEmpty()) {
            return;
        }

        try {
            int inserted = mapper.insertBatch(batchList);
            log.debug("批量插入 {} 条数据, 成功 {} 条", batchList.size(), inserted);
        } catch (Exception e) {
            failedCount.addAndGet(batchList.size());
            log.error("批量插入失败: {}", e.getMessage());
        } finally {
            batchList.clear();
        }
    }

    /**
     * 数据转换方法 - 根据你的Excel列顺序调整
     */
    private AssetTargetInfo convertToEntity(List<Object> row, int sheetIndex, int rowIndex) {
        AssetTargetInfo entity = new AssetTargetInfo();

        // 根据你的Excel列顺序设置字段
        // 这里需要根据你的实际Excel结构调整
        if (row.size() > 0) entity.setTargetName(row.get(0).toString());
        if (row.size() > 1) entity.setTargetDefinition(row.get(1).toString());
        if (row.size() > 2) entity.setTargetStatsCoverage(row.get(2).toString());
        if (row.size() > 3) entity.setCntOrg(row.get(3).toString());

        // 生成唯一资产编号
        String assetNo = "MT" + String.format("%09d", assetNoCounter.getAndIncrement());
        entity.setAssetNo(assetNo);

        // 设置系统字段
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        entity.setDelFlag(0L);

        return entity;
    }

    public int getProcessedCount() {
        return processedCount.get();
    }

    public int getFailedCount() {
        return failedCount.get();
    }
}